<template>
  <div class="space-y-6">
    <!-- 页面标题 -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex items-center justify-between">
        <div>
          <h2 class="text-lg font-medium text-gray-900">{{ $t('dashboard.myPosts') }}</h2>
          <p class="mt-1 text-sm text-gray-600">
            {{ $t('dashboard.myPostsDescription') }}
          </p>
        </div>
        <router-link
          to="/post/create"
          class="btn-primary"
        >
          {{ $t('post.create') }}
        </router-link>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="bg-white rounded-lg shadow">
      <div v-if="loading" class="flex justify-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>

      <div v-else-if="posts.length > 0" class="divide-y divide-gray-200">
        <div
          v-for="post in posts"
          :key="post.id"
          class="p-6 hover:bg-gray-50"
        >
          <div class="flex items-start space-x-4">
            <!-- 宠物照片 -->
            <img
              v-if="post.pet?.photo_url"
              :src="getFullImageUrl(post.pet.photo_url)"
              :alt="post.pet.name"
              class="w-16 h-16 object-contain bg-gray-100 rounded-lg flex-shrink-0"
            />
            <div
              v-else
              class="w-16 h-16 bg-gray-200 rounded-lg flex items-center justify-center flex-shrink-0"
            >
              <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>

            <!-- 帖子信息 -->
            <div class="flex-1 min-w-0">
              <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">
                  {{ post.pet?.name }}
                </h3>
                <span
                  :class="[
                    'px-2 py-1 text-xs font-medium rounded-full',
                    post.post_status === 'searching'
                      ? 'bg-yellow-100 text-yellow-800'
                      : post.post_status === 'found'
                      ? 'bg-green-100 text-green-800'
                      : 'bg-gray-100 text-gray-800'
                  ]"
                >
                  {{ $t(POST_STATUS_LABELS[post.post_status]) }}
                </span>
              </div>

              <div class="mt-1 flex items-center text-sm text-gray-500 space-x-4">
                <span>{{ post.pet?.species }}</span>
                <span>{{ post.pet?.color }}</span>
                <span>{{ formatDate(post.created_at) }}</span>
              </div>

              <p class="mt-2 text-sm text-gray-600">
                {{ $t('dashboard.lostLocation', { location: post.last_seen_location }) }}
              </p>

              <!-- 操作按钮 -->
              <div class="mt-4 flex items-center space-x-4">
                <router-link
                  :to="`/posts/${post.id}`"
                  class="text-primary-600 hover:text-primary-700 text-sm font-medium"
                >
                  {{ $t('post.view') }}
                </router-link>

                <button
                  @click="viewSightings(post)"
                  class="text-gray-600 hover:text-gray-700 text-sm font-medium"
                >
                  {{ $t('dashboard.viewSightings') }}
                </button>

                <div class="relative">
                  <select
                    :value="post.post_status"
                    @change="updatePostStatus(post.id, ($event.target as HTMLSelectElement).value as any)"
                    class="text-sm border-gray-300 rounded-md focus:ring-primary-500 focus:border-primary-500"
                  >
                    <option value="searching">{{ $t('post.status.searching') }}</option>
                    <option value="found">{{ $t('post.status.found') }}</option>
                    <option value="closed">{{ $t('post.status.closed') }}</option>
                  </select>
                </div>

                <button
                  @click="deletePost(post)"
                  class="text-red-600 hover:text-red-700 text-sm font-medium"
                >
                  {{ $t('post.delete') }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.5-.9-6.1-2.3" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('common.noData') }}</h3>
        <p class="mt-1 text-sm text-gray-500">
          {{ $t('dashboard.noPosts') }}
        </p>
        <div class="mt-6">
          <router-link
            to="/post/create"
            class="btn-primary"
          >
            {{ $t('post.create') }}
          </router-link>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1">
      <Pagination
        :current-page="pagination.page"
        :total-pages="pagination.totalPages"
        :total="pagination.total"
        @page-change="handlePageChange"
      />
    </div>

    <!-- 线索查看模态框 -->
    <SightingsModal
      v-if="showSightingsModal && selectedPost"
      :post="selectedPost"
      @close="closeSightingsModal"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { postService } from '@/services/posts'
import Pagination from '@/components/Pagination.vue'
import SightingsModal from '@/components/SightingsModal.vue'
import { formatDate, getFullImageUrl } from '@/utils/helpers'
import type { Post } from '@/types'
import { POST_STATUS_LABELS, PAGINATION } from '@/constants'

const { t } = useI18n()

// 状态
const loading = ref(false)
const posts = ref<Post[]>([])
const pagination = ref({
  page: 1,
  limit: PAGINATION.DEFAULT_LIMIT,
  total: 0,
  totalPages: 0,
})

// 线索查看相关状态
const showSightingsModal = ref(false)
const selectedPost = ref<Post | null>(null)

// 方法
const loadPosts = async () => {
  try {
    loading.value = true

    const response = await postService.getMyPosts({
      page: pagination.value.page,
      limit: pagination.value.limit,
    })

    if (response.success && response.data) {
      // 服务器返回的格式是 { success, message, data: [...], pagination: {...} }
      posts.value = response.data as Post[]
      // 从响应中获取分页信息
      if ('pagination' in response) {
        pagination.value = {
          page: (response as any).pagination.currentPage,
          limit: (response as any).pagination.itemsPerPage,
          total: (response as any).pagination.totalItems,
          totalPages: (response as any).pagination.totalPages,
        }
      }
    }
  } catch (error) {
    console.error(t('dashboard.loadPostsFailed'), error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  loadPosts()
}

const updatePostStatus = async (postId: number, status: 'searching' | 'found' | 'closed') => {
  try {
    const response = await postService.updateStatus(postId, status)

    if (response.success) {
      // 更新本地状态
      const post = posts.value.find(p => p.id === postId)
      if (post) {
        post.post_status = status
      }
    } else {
      alert(t('dashboard.updateStatusFailed', { message: response.message }))
    }
  } catch (error) {
    console.error('更新帖子状态失败:', error)
    alert(t('dashboard.updateStatusFailedRetry'))
  }
}

const deletePost = async (post: Post) => {
  if (!confirm(t('dashboard.confirmDeletePost', { name: post.pet?.name || t('common.unknown') }))) {
    return
  }

  try {
    const response = await postService.delete(post.id)

    if (response.success) {
      // 从列表中移除
      posts.value = posts.value.filter(p => p.id !== post.id)
      pagination.value.total--
    } else {
      alert(t('dashboard.deleteFailed', { message: response.message }))
    }
  } catch (error) {
    console.error('删除帖子失败:', error)
    alert(t('dashboard.deleteFailedRetry'))
  }
}

const viewSightings = (post: Post) => {
  selectedPost.value = post
  showSightingsModal.value = true
}

const closeSightingsModal = () => {
  showSightingsModal.value = false
  selectedPost.value = null
}

onMounted(() => {
  loadPosts()
})
</script>
